import {useStore} from "@/store/user"
import {createRouter,createWebHashHistory,RouteRecordRaw} from "vue-router"
import Login from "../view/Login/Login.vue"
import {UserInfoAPI}from "@/http/api/index"
const routes:RouteRecordRaw[]= [
    {
        path:"/login",
        name:"Login",
        component:Login
    },{
        path:"/home",
        name:"Home",
        component:()=>import("../view/Home/index.vue"),
        children:[{
            path:"home",
            component:()=>import("../view/Home/index.vue")
        }]
    }
]

const router = createRouter({
    routes,
    history:createWebHashHistory()
})

router.beforeEach((to,from,next)=>{
    const token  = localStorage.getItem("token")
    const store = useStore()
    if(token&&store.menus.length===0){
        UserInfoAPI().then((res)=>{
            // console.log("res-router1",res);
            
            if(res.code===200){
                store.menus=res.data.menus
                // console.log("res-router",res.data.menus);
                store.myrouterdata.forEach((item)=>{
                    router.addRoute({
                        path:"/"+item.name,
                        component:()=>import("../view/Home/index.vue"),
                        children:item.children.map((item1)=>({path:item1.name,component:()=>import(`../view/${item.name}/${item1.name}.vue`)}))
                    })
                })
                next(to.fullPath)
            }
        })

    }else{
    next()    
    }
    
})

export default router